<template>
  <div class="health-manage-page">
    <el-card class="main-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><DocumentChecked /></el-icon>
            <span class="header-title">健康档案管理</span>
          </div>
          <el-button type="primary" @click="openDialog()" :icon="Plus">
            新增记录
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-alert
          v-if="!animalId"
          type="info"
          :closable="false"
          show-icon
          style="margin-bottom: 16px;"
        >
          请先选择动物以查看健康档案
        </el-alert>
        <el-select 
          v-model="animalId" 
          placeholder="选择动物（必选）" 
          filterable
          style="width: 250px;"
          @change="handleSearch"
        >
          <el-option 
            v-for="a in animalList" 
            :key="a.id" 
            :label="`${a.name} (${a.species})`" 
            :value="a.id" 
          />
        </el-select>
        <el-button @click="handleReset" :icon="Refresh">重置</el-button>
      </div>

      <!-- 表格 -->
      <el-table 
        :data="filteredList" 
        border 
        stripe
        v-loading="loading"
        style="width: 100%; margin-top: 20px;"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="animalName" label="动物名称" width="150" />
        <el-table-column prop="checkDate" label="检查日期" width="150" align="center">
          <template #default="{ row }">
            {{ formatDate(row.checkDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="disease" label="疾病记录" min-width="200" show-overflow-tooltip />
        <el-table-column prop="vaccine" label="疫苗接种" min-width="200" show-overflow-tooltip />
        <el-table-column prop="notes" label="备注" min-width="250" show-overflow-tooltip />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="openDialog(row)"
              :icon="Edit"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="del(row.id)"
              :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty 
        v-if="!loading && filteredList.length === 0" 
        description="暂无数据"
        style="margin: 40px 0;"
      />
    </el-card>

    <!-- 编辑弹窗 -->
    <el-dialog 
      v-model="visible" 
      :title="form.id ? '编辑健康档案' : '新增健康档案'" 
      width="700px"
      @close="handleDialogClose"
    >
      <el-form 
        ref="formRef"
        :model="form" 
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="动物" prop="animalId">
          <el-select 
            v-model="form.animalId" 
            placeholder="请选择动物"
            filterable
            style="width: 100%;"
          >
            <el-option 
              v-for="a in animalList" 
              :key="a.id" 
              :label="`${a.name} (${a.species})`" 
              :value="a.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="检查日期" prop="checkDate">
          <el-date-picker
            v-model="form.checkDate"
            type="date"
            placeholder="选择检查日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item label="疾病记录">
          <el-input 
            v-model="form.disease" 
            type="textarea"
            :rows="3"
            placeholder="请输入疾病记录，如无疾病请填写'健康'"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="疫苗接种">
          <el-input 
            v-model="form.vaccine" 
            type="textarea"
            :rows="3"
            placeholder="请输入疫苗接种记录，如已接种的疫苗类型和时间"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input 
            v-model="form.notes" 
            type="textarea"
            :rows="4"
            placeholder="请输入其他备注信息"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="save" :loading="saving">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { DocumentChecked, Plus, Refresh, Edit, Delete } from '@element-plus/icons-vue';
import axios from "axios";

const list = ref([]);
const animalList = ref([]);
const animalId = ref(null);
const visible = ref(false);
const loading = ref(false);
const saving = ref(false);
const form = ref({});
const formRef = ref(null);

const formRules = {
  animalId: [{ required: true, message: '请选择动物', trigger: 'change' }],
  checkDate: [{ required: true, message: '请选择检查日期', trigger: 'change' }]
};

// 不再需要 filteredList，因为后端已经按 animalId 过滤
const filteredList = computed(() => list.value);

const formatDate = (date) => {
  if (!date) return '-';
  return date;
};

const getAnimalList = async () => {
  try {
    const res = await axios.get("http://localhost:8080/api/admin/animal/list");
    if (res.data.code === 200) {
      animalList.value = res.data.data || [];
    } else {
      ElMessage.error('获取动物列表失败');
    }
  } catch (error) {
    console.error('获取动物列表失败:', error);
    ElMessage.error('获取动物列表失败');
  }
};

const getList = async () => {
  if (!animalId.value) {
    list.value = [];
    return;
  }
  
  loading.value = true;
  try {
    const res = await axios.get("http://localhost:8080/api/admin/health/list", { 
      params: { animalId: animalId.value } 
    });
    if (res.data.code === 200) {
      list.value = res.data.data || [];
    } else {
      ElMessage.error(res.data.msg || '获取数据失败');
      list.value = [];
    }
  } catch (error) {
    console.error('获取健康档案失败:', error);
    ElMessage.error('获取数据失败，请确保已选择动物');
    list.value = [];
  } finally {
    loading.value = false;
  }
};

const openDialog = (row) => {
  if (row) {
    form.value = { ...row };
  } else {
    form.value = {
      animalId: null,
      checkDate: '',
      disease: '',
      vaccine: '',
      notes: ''
    };
  }
  visible.value = true;
};

const handleDialogClose = () => {
  formRef.value?.resetFields();
  form.value = {};
};

const save = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请完善表单信息');
      return;
    }
    
      saving.value = true;
    try {
      const isUpdate = form.value.id;
      const url = isUpdate
        ? "http://localhost:8080/api/admin/health/update" 
        : "http://localhost:8080/api/admin/health/add";
      
      const method = isUpdate ? 'put' : 'post';
      const res = await axios[method](url, form.value);
      if (res.data.code === 200) {
        ElMessage.success("保存成功");
        visible.value = false;
        getList();
      } else {
        ElMessage.error(res.data.msg || '保存失败');
      }
    } catch (error) {
      console.error('保存失败:', error);
      ElMessage.error('保存失败');
    } finally {
      saving.value = false;
    }
  });
};

const del = async (id) => {
  try {
    await ElMessageBox.confirm("确定删除该记录吗？", "提示", { 
      type: "warning",
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    });
    
    const res = await axios.delete(`http://localhost:8080/api/admin/health/delete/${id}`);
    if (res.data.code === 200) {
      ElMessage.success("删除成功");
      getList();
    } else {
      ElMessage.error(res.data.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

const handleSearch = () => {
  getList();
};

const handleReset = () => {
  animalId.value = null;
  list.value = [];
};

onMounted(() => {
  getAnimalList();
  // 不自动加载列表，需要先选择动物
});
</script>

<style scoped>
.health-manage-page {
  width: 100%;
}

.main-card {
  min-height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 22px;
  color: #67C23A;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>